package com.my.jli.controller;

import com.my.jli.Service.HomeworkService;
import com.my.jli.entity.Homework;
import com.my.jli.entity.HomeworkAndStudent;
import com.my.jli.util.MyZipUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName HomeworkController
 * @Description
 * @Author MaYu
 * @Date 2022/5/10 21:39
 * @Version 1.0
 **/
@Controller
@RequestMapping("/homework")
public class HomeworkController {

    @Value("${file-save-path}")
    private String fileSavePath;

    Logger logger = LoggerFactory.getLogger(HomeworkController.class);

    HomeworkService homeworkService;
    @Autowired
    public void setHomeworkService(HomeworkService homeworkService) {
        this.homeworkService = homeworkService;
    }

    @RequestMapping("/downloadZip")
    public void downZip(Integer hid, HttpServletResponse response){
        Homework homework = homeworkService.getById(hid);
        if (homework != null){
            String homeworkPath = "/作业编号_" + homework.getId();
            String dirPath = fileSavePath + "/homework" + homeworkPath;
            //创建临时文件夹
            try {
                //附件下载
                response.setContentType("application/zip");
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("作业编号_" + homework.getId() + ".zip", "UTF-8"));
                //调用工具类下载zip压缩包
                ServletOutputStream outputStream = response.getOutputStream();
                try {
                    MyZipUtil.toZip(dirPath, outputStream);
                } catch (Exception e){
                    e.printStackTrace();
                }
                //关闭流
                outputStream.close();
                logger.info("下载了zip文件：作业编号_" + homework.getId());
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("文件下载失败：作业编号_" + homework.getId());
            }
        }
    }
}
